package one.stand.service.impl;

import com.jmp.base.LogApi;
import com.jmp.base.dto.LogAddRequest;
import com.jmp.feign.LogFeign;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.mapper.CompanyServiceMapperExt;
import one.stand.model.CompanyService;
import one.stand.service.CompanyServiceService;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import one.stand.util.MoneyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class CompanyServiceServiceImpl implements CompanyServiceService {
    @Autowired
    private LogFeign logFeign;
    @Autowired
    private CompanyServiceMapperExt companyServiceMapperExt;

    /**
     * 初始化时，默认1张名片
     */
    private Integer NUM_DEFAULT = 1;

    @Override
    public void init(Integer companyId, boolean clientJxs) {
        CompanyService companyServiceModel = new CompanyService();
        companyServiceModel.setCompanyId(companyId);
        companyServiceModel.setPurchaseNum(NUM_DEFAULT);
        companyServiceModel.setPurchaseType(PURCHASE_TYPE_BUY);
        companyServiceModel.setType(1);
        companyServiceModel.setHistoryNum(0);
        companyServiceModel.setAvailableNum(NUM_DEFAULT);
        companyServiceModel.setCurrentNum(NUM_DEFAULT);
        companyServiceModel.setCreateTime(DateUtil.currentDate());
        if (clientJxs) {
            companyServiceModel.setEndTime(DateUtil.getDate(companyServiceModel.getCreateTime(), Calendar.YEAR, 1));
        } else {
            companyServiceModel.setEndTime(DateUtil.getBeforeOrAfterDate(companyServiceModel.getCreateTime(), 3));
        }
        companyServiceModel.setServiceState(0);
        companyServiceMapperExt.insertSelective(companyServiceModel);
    }

    @Override
    @Transactional
    public void add(Integer companyId, Integer purchaseNum, String endTime, Integer payNum, Integer userId) {
        // 查询公司购买服务数
        CompanyService model = getMain(companyId);

        Date endTimeDate;
        try {
            endTimeDate = DateUtil.formatter.parse(endTime + " 23:59:59");
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            return;
        }

        CompanyService companyServiceModel = new CompanyService();
        companyServiceModel.setCompanyId(companyId);
        companyServiceModel.setPurchaseType(PURCHASE_TYPE_BUY);
        // 1,当前,0记录
        companyServiceModel.setType(1);
        // 支付金额
        companyServiceModel.setPayNum(payNum);
        // 本次操作数量
        companyServiceModel.setPurchaseNum(purchaseNum);
        // 当前总购买数
        companyServiceModel.setCurrentNum(purchaseNum);
        companyServiceModel.setCreateTime(DateUtil.currentDate());
        // 到期时间
        companyServiceModel.setEndTime(endTimeDate);
        if (model == null) {
            // 状态：0未授权，1以授权（花钱购买服务）
            companyServiceModel.setServiceState(Objects.isNull(payNum) || payNum <= 0 ? 0 : 1);
            // 操作前可用数量
            companyServiceModel.setHistoryNum(0);
            // 当前可用数量
            companyServiceModel.setAvailableNum(purchaseNum);
            companyServiceMapperExt.insertSelective(companyServiceModel);
        } else {
            // 判断到期时间
//            if (!(endTimeDate.compareTo(model.getEndTime()) >= 0)) {
//                return ResultModel.fail("到期时间不能小于:" + DateUtil.format.format(model.getEndTime()));
//            }
            // 状态：0未授权，1以授权（花钱购买服务）
            boolean fal = (model.getServiceState() != null && model.getServiceState() == 1) || (payNum != null && payNum > 0);
            companyServiceModel.setServiceState(fal ? 1 : 0);
            // 操作前可用数量
            companyServiceModel.setHistoryNum(model.getAvailableNum());
            // 当前可用数量(本次购买总数-（上次购买数量-上次剩余数量）)
            companyServiceModel.setAvailableNum(purchaseNum - (model.getCurrentNum() - model.getAvailableNum()));
            companyServiceMapperExt.insertSelective(companyServiceModel);
            // 修改之前的名片服务记录表状态为记录
            companyServiceMapperExt.updateByPrimaryKeySelective(new CompanyService() {{
                setType(0);
                setServiceId(model.getServiceId());
            }});
        }


        // 增加操作记录
        StringBuilder content = new StringBuilder("购买总数：").append(purchaseNum);
        if (payNum != null && payNum > 0) {
            content.append("；支付金额：").append(MoneyUtil.getWithUnit(payNum));
        }
        content.append("；到期时间：").append(endTime);
        LogAddRequest logAddRequest = LogAddRequest.builder()
                .type(LogApi.TYPE_SERVER_BUY)
                .userId(userId)
                .companyId(companyId)
                .content(content.toString())
                .date(DateUtil.currentDate())
                .build();
        logFeign.add(logAddRequest);
    }

    @Override
    @Transactional
    public void sub(Integer companyId) {
        // 查询公司购买服务数
        CompanyService companyServiceModel = getMain(companyId);
        AssertUtil.nonNull(companyServiceModel, "操作失败，未找到公司购买服务记录信息~!");
        // 公司购买名片服务记录表
        Integer serviceId = companyServiceModel.getServiceId();
        companyServiceModel.setHistoryNum(companyServiceModel.getAvailableNum());
        companyServiceModel.setAvailableNum(companyServiceModel.getAvailableNum() + 1);
        companyServiceModel.setCreateTime(DateUtil.currentDate());
        companyServiceModel.setPurchaseType(PURCHASE_TYPE_QUIT);
        companyServiceModel.setServiceId(null);
        int r = companyServiceMapperExt.insertSelective(companyServiceModel);
        AssertUtil.isTrue(r == 1, ResultEnum.FAIL);
        // 修改之前的名片服务记录表为记录
        companyServiceMapperExt.updateByPrimaryKeySelective(new CompanyService() {{
            setType(0);
            setServiceId(serviceId);
        }});
    }

    @Override
    @Transactional
    public void use(Integer companyId) {
        CompanyService companyServiceModel = getMain(companyId);
        AssertUtil.isFalse(companyServiceModel == null || companyServiceModel.getAvailableNum() <= 0, "可用名片数不足，请前去购买服务名片数~！");

        // 公司购买名片服务记录表
        Integer serviceId = companyServiceModel.getServiceId();
        companyServiceModel.setHistoryNum(companyServiceModel.getAvailableNum());
        companyServiceModel.setAvailableNum(companyServiceModel.getAvailableNum() - 1);
        companyServiceModel.setCreateTime(DateUtil.currentDate());
        companyServiceModel.setPurchaseType(PURCHASE_TYPE_USE);
        companyServiceModel.setServiceId(null);
        int r = companyServiceMapperExt.insertSelective(companyServiceModel);
        if (r > 0) {
            // 修改之前的名片服务记录表为记录
            companyServiceMapperExt.updateByPrimaryKeySelective(new CompanyService() {{
                setType(0);
                setServiceId(serviceId);
            }});
        }
    }

    @Override
    @Transactional
    public void clear(Integer companyId) {
        CompanyService companyServiceModel = getMain(companyId);
        if (null != companyServiceModel) {
            companyServiceModel.setType(0);
            companyServiceMapperExt.updateByPrimaryKeySelective(companyServiceModel);
            log.info("修改名片可用数量：{}", companyServiceModel.toString());

            companyServiceModel.setPurchaseNum(companyServiceModel.getCurrentNum() - companyServiceModel.getAvailableNum());
            companyServiceModel.setPurchaseType(PURCHASE_TYPE_QUIT);
            companyServiceModel.setType(1);
            companyServiceModel.setHistoryNum(companyServiceModel.getAvailableNum());
            companyServiceModel.setAvailableNum(companyServiceModel.getCurrentNum());
            companyServiceModel.setCreateTime(DateUtil.currentDate());
            companyServiceModel.setServiceId(null);
            companyServiceMapperExt.insertSelective(companyServiceModel);
            log.info("插入名片可用数量：{}", companyServiceModel.toString());
        }
    }

    @Override
    public Long check(Integer companyId) {
        CompanyService model = getMain(companyId);
        if (model == null || model.getEndTime() == null) return 0L;
        Long days = DateUtil.uitl(model.getEndTime());
        return days > 0 ? days : 0L;
    }

    private CompanyService getMain(Integer companyId) {
        return companyServiceMapperExt.select(companyId, 1);
    }
}
